package com.egg.eggtv.ui.activity;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import com.egg.eggtv.BuildConfig;
import com.egg.eggtv.R;
import com.egg.eggtv.base.BaseActivity;
import com.egg.eggtv.mvp.IMainView;
import com.egg.eggtv.mvp.MainPresenter;
import com.egg.eggtv.pojo.BannerEntity;
import com.egg.eggtv.pojo.ShopEntity;
import com.egg.eggtv.pojo.VideoEntity;
import com.egg.eggtv.ui.JSInterface;
import com.egg.eggtv.ui.adapter.ADA_ShopList;
import com.egg.eggtv.ui.dialog.AlertDialog;
import com.egg.eggtv.ui.widgets.GlideImageLoader;
import com.egg.eggtv.ui.widgets.PlayTextureView;
import com.egg.eggtv.util.API;
import com.egg.eggtv.util.DeviceIdUtils;
import com.egg.eggtv.util.FileUtil;
import com.egg.eggtv.util.LogUtil;
import com.egg.eggtv.util.MediaPlayerTool;
import com.egg.eggtv.util.NetWorkUtil;
import com.egg.eggtv.util.SpManager;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by JoeLjt on 2019/10/30.
 * Email: lijiateng1219@gmail.com
 * Description:
 */

public class MainActivity extends BaseActivity implements IMainView {

    private static final String KEY = "sn_key";
    private static final String KEY_SHOP_NAME = "key_shop_name";

    private String snKey;
    private MainPresenter mPresenter;
    private MediaPlayerTool mMediaPlayerTool;

    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.ll_video)
    LinearLayout llVideo;
    @BindView(R.id.video_view)
    PlayTextureView videoView;
    @BindView(R.id.banner)
    Banner banner;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mMediaPlayerTool = MediaPlayerTool.getInstance();
        mPresenter = new MainPresenter(this, this);

        snKey = SpManager.getInstance().getString(KEY);
        if (TextUtils.isEmpty(snKey)) {
            mPresenter.requestShopList(API.COMPANY_ID);
        } else {
            mPresenter.getShopInfoByDeviceId(snKey);
        }

        initWebViewConfig();

    }

    private void initWebViewConfig() {

        final WebSettings webSettings = webView.getSettings();

        // 自适应大小
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);

        //允许js代码
        webSettings.setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JSInterface(this, mHandler), "Android");

        //允许SessionStorage/LocalStorage存储
        webSettings.setDomStorageEnabled(true);

        //放缩
        webSettings.setSupportZoom(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setBuiltInZoomControls(false);
        webView.setInitialScale(100);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        // 禁用 file 协议；
        webSettings.setAllowFileAccess(false);
        webSettings.setAllowFileAccessFromFileURLs(false);
        webSettings.setAllowUniversalAccessFromFileURLs(false);
        //设置缓存
        if (NetWorkUtil.isConnected(this)) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }

        webSettings.setAppCacheEnabled(true);
        webSettings.setAppCachePath(getCacheDir().getAbsolutePath());
        //自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        //设置编码
        webSettings.setDefaultTextEncodingName("utf8");

        //滑动条
        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(false);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                webView.setVisibility(View.VISIBLE);
            }
        });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initTvDialog(List<ShopEntity> shopList) {

        if (shopList == null || shopList.size() == 0) {
            Toast.makeText(MainActivity.this, "该公司下暂无门店信息！", Toast.LENGTH_LONG).show();
            return;
        }

        final AlertDialog tvDialog = new AlertDialog.Builder(this)
                .setContentView(R.layout.dialog_tv)
                .setWidthAndHeight(400, -2)
                .create();

        final RecyclerView rvShop = tvDialog.getView(R.id.rv_shop);
        rvShop.setLayoutManager(new LinearLayoutManager(this));

        final ADA_ShopList shopListAdapter = new ADA_ShopList(this, shopList);
        rvShop.setAdapter(shopListAdapter);

        shopListAdapter.setListener(new ADA_ShopList.OnListener() {
            @Override
            public void onItemFocusChanged(View rootView, int position) {
                // 焦点变化的监听
                rvShop.scrollToPosition(position);
            }

            @Override
            public void onBackButtonClicked() {
                tvDialog.dismiss();
                finish();
            }

            @Override
            public void onCenterButtonClicked(ShopEntity shopEntity) {
                mPresenter.bindDeviceWithShop(shopEntity, DeviceIdUtils.randomUtil());
                tvDialog.dismiss();
                Toast.makeText(MainActivity.this,
                        String.format("正在绑定【%s】，请稍候", shopEntity.getValue()), Toast.LENGTH_LONG).show();
            }

        });

        tvDialog.show();
    }

    @Override
    public void saveDeviceId(String deviceId, String shopName) {
        SpManager.getInstance().put(KEY, deviceId);
        SpManager.getInstance().put(KEY_SHOP_NAME, shopName);
        Toast.makeText(MainActivity.this, "保存门店信息成功~", Toast.LENGTH_LONG).show();
    }

    @Override
    public void showTvView(String shopId) {

        String shopName = SpManager.getInstance().getString(KEY_SHOP_NAME);
        if (!TextUtils.isEmpty(shopName)) {
            Toast.makeText(MainActivity.this,
                    String.format("正在连接【%s】,请稍候", shopName), Toast.LENGTH_LONG).show();
        }

        final String url;
        if (BuildConfig.DEBUG)
            url = "http://test.mumzone.cn:97/#/advertisingPictures" + getShopIdParams(shopId);
        else
            url = "http://e.mumzone.cn/#/advertisingPictures" + getShopIdParams(shopId);

        LogUtil.i("启动WebAc,加载Url ");
        LogUtil.e("TV", "Url = " + url);
        webView.loadUrl(url);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LogUtil.i("延时10秒重新加载Url");
                webView.loadUrl(url);
            }
        }, 10000);

        mPresenter.getBannerPic();
        mPresenter.getPlayVideo();

    }

    public String getShopIdParams(String shopId) {
        return String.format("?shopId=%s&companyId=%s", shopId, API.COMPANY_ID);
    }

    @Override
    public void playVideo(VideoEntity videoEntity) {

        if (videoEntity != null) {
            if (videoEntity.getList() != null && videoEntity.getList().size() > 0) {
                playVideoWithUri(videoEntity.getList().get(0).getImgUrl());
            } else {
                mPresenter.getDefaultVideoUrl();
            }
        } else {
            playVideoWithUri(null);
        }

    }

    @Override
    public void playDefaultVideo(String defaultUrl) {
        playVideoWithUri(defaultUrl);
    }

    private void playVideoWithUri(String targetPath) {

        mMediaPlayerTool.initMediaPLayer();

        File file = new File(Environment.getExternalStorageDirectory() + "/default_video.mp4");
        if (!file.exists()) {
            FileUtil.copyFile(getApplicationContext());
        }

        if (TextUtils.isEmpty(targetPath)) {
            targetPath = file.getAbsolutePath();
        }

        mMediaPlayerTool.setDataSource(targetPath);

        mMediaPlayerTool.setVolume(50);
        MediaPlayerTool.VideoListener videoListener = new MediaPlayerTool.VideoListener() {
            @Override
            public void onStart() {
                videoView.setVideoSize(mMediaPlayerTool.getVideoWidth(), mMediaPlayerTool.getVideoHeight());
            }
        };
        mMediaPlayerTool.setVideoListener(videoListener);

        videoView.resetTextureView();
        mMediaPlayerTool.setPlayTextureView(videoView);
        mMediaPlayerTool.setSurfaceTexture(videoView.getSurfaceTexture());
        mMediaPlayerTool.setLooping(true);
        mMediaPlayerTool.prepare();

    }

    @Override
    public void loadUpBannerPicture(List<BannerEntity> bannerList) {

        if (bannerList == null) {
            bannerList = new ArrayList<>();
        }

        banner.setImageLoader(new GlideImageLoader());
        banner.setImages(bannerList);
        banner.isAutoPlay(true);
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        banner.start();
    }


}
